import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
import common from '../../lib/common/common.js';

const storagePath = './temp/bilibili';
const storagePath2 = './plugins/bililivePush-plugin/data/bilibili';   // 配置文件路径

export class ExamplePlugin extends plugin {
    constructor() {
        super({
            name: "b站功能",
            desc: "扫码登录",
            event: "message",
            priority: -Infinity,
            rule: [
                {
                    reg: /^导入我的直播推送$/,
                    fnc: "bililpush"
                }
            ]
        });
        this.storagePath = storagePath;
        this.storagePath2 = storagePath2;
    }

    async bililpush(e) {
        const userId = e.user_id;
        const groupId = e.group_id;
        const userCookiesPath = path.join(this.storagePath, `user_cookies.json`);
        let userCookies;

        try {
            userCookies = JSON.parse(fs.readFileSync(userCookiesPath, 'utf8'))[userId];
        } catch (err) {
            logger.error("Failed to read or parse user_cookies.json", err);
            return;
        }

        if (!userCookies) {
            e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
            return;
        }

        const cookie = `SESSDATA=${userCookies.SESSDATA}; csrf=${userCookies.csrf}; bili_ticket=${userCookies.bili_ticket}`;
        const totalPageSize = 10; 
        let totalPages = 1;
        let upCount = 0; 

        let liveData; 
        let liveData2 = { data: {}, version: 1 }; 
        const liveJsonPath = path.join(this.storagePath2, 'live.json');

        try {
            if (fs.existsSync(liveJsonPath)) {
                const fileContent = fs.readFileSync(liveJsonPath, 'utf8');
                liveData = JSON.parse(fileContent);
                if (!liveData.data) {
                    liveData.data = {}; 
                }
                if (!liveData.version) {
                    liveData.version = 1; 
                }
            } else {
               
                liveData = { data: {}, version: 1 };
                fs.writeFileSync(liveJsonPath, JSON.stringify(liveData, null, 2), 'utf8');
                logger.info("Created new live.json with default structure.");
            }
        } catch (err) {
            logger.error("Error reading or parsing live.json", err);
            liveData = { data: {}, version: 1 };
        }

        for (let page = 1; page <= totalPages; page++) {
            const params = new URLSearchParams({
                'page': page.toString(),
                'page_size': totalPageSize.toString(),
                'ignoreRecord': '1',
                'hit_ab': 'true'
            });
            await common.sleep(1000);
            try {
                const response = await fetch(`https://api.live.bilibili.com/xlive/web-ucenter/user/following?${params}`, {
                    headers: {
                        'Cookie': cookie
                    }
                });
                const result = await response.json();

                if (result.code === 0) {
                    totalPages = Math.ceil(result.data.count / totalPageSize);
                    upCount += result.data.list.length;

                    result.data.list.forEach(up => {
                        const uid = up.uid;
                        const room_id = up.roomid || '';

                      
                        if (!liveData.data[uid]) {
                            liveData.data[uid] = {
                                "uid": uid,
                                "room_id": room_id,
                                "group": {}
                            };
                        }

                        if (!liveData.data[uid].group[groupId]) {
                            liveData.data[uid].group[groupId] = [];
                        }

                        if (!liveData.data[uid].group[groupId].includes(userId)) {
                            liveData.data[uid].group[groupId].push(userId);
                        }

                     
                        if (!liveData2.data[uid]) {
                            liveData2.data[uid] = {
                                "uid": uid,
                                "room_id": room_id,
                                "face": up.face, 
                                "uname": up.uname, 
                                "area_name_v2": up.area_name_v2, 
                                "room_news": up.room_news, 
                                "title": up.title,
                                "record_live_time": up.record_live_time,
                                "group": {}
                            };
                        }

                        if (!liveData2.data[uid].group[groupId]) {
                            liveData2.data[uid].group[groupId] = [];
                        }

                        if (!liveData2.data[uid].group[groupId].includes(userId)) {
                            liveData2.data[uid].group[groupId].push(userId);
                        }
                    });

                  
                    fs.writeFileSync(liveJsonPath, JSON.stringify(liveData, null, 2), 'utf8');
                } else {
                    logger.error('API Error:', result.message);
                }
            } catch (err) {
                logger.error("Error fetching live list:", err);
            }
        }

        const mdTemplate = ups => `
![直播间封面](${ups.face})
---
### 直播信息

- **房间号**: ${ups.room_id}
- **用户UID**: ${ups.uid}
- **主播名**: ${ups.uname}
- **频道名称**: ${ups.area_name_v2 || '未知'}
- **房间公告**: ${ups.room_news || '无'}
- **直播标题**: ${ups.title || '未设置'}
- **上次直播结束时间**: ${new Date(ups.record_live_time * 1000).toLocaleString()}
`;

        
        async function buildForwardMsgData(e, liveData2, userId, groupId) {
            const messages = [];
            let currentBatch = { type: 'node', data: { nickname: e.sender.nickname, user_id: e.user_id, content: [] } };
            let currentCount = 0;

         
            for (const ups of Object.values(liveData2.data).filter(data => data.group[groupId]?.includes(userId))) {
                if (currentCount >= 99) {
                 
                    messages.push(currentBatch);
                    currentBatch = { type: 'node', data: { nickname: e.sender.nickname, user_id: e.user_id, content: [] } };
                    currentCount = 0;
                }

               
                currentBatch.data.content.push({
                    type: 'node',
                    data: {
                        nickname: e.sender.nickname,
                        user_id: userId,
                        content: [{
                            type: 'markdown',
                            data: {
                                content: mdTemplate(ups)
                            }
                        }]
                    }
                });
                currentCount++;
            }

            if (currentBatch.data.content.length > 0) {
                messages.push(currentBatch);
            }

            return {
                group_id: groupId,
                messages: messages,
                news: [{ text: "b站关注主播" },{ text: "成功添加推送" }]
            };
        }

        // 发送消息
        try {
            const forwardMsgData = await buildForwardMsgData(e, liveData2, userId, groupId);
            await e.bot.sendApi('send_group_forward_msg', forwardMsgData);
        } catch (err) {
            logger.error("Error sending message:", err);
        }
    }
}